package com.hkunderground.blogger;

import java.io.IOException;

import java.net.URL;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.*;

import com.google.gdata.client.GoogleService;
import com.google.gdata.data.Entry;
import com.google.gdata.data.HtmlTextConstruct;
import com.google.gdata.data.TextConstruct;
import com.google.gdata.data.TextContent;
import com.google.gdata.util.ServiceException;
import com.hkunderground.blogger.helper.ConstantHelper;
import com.hkunderground.blogger.helper.PropertiesHelper;
import com.hkunderground.blogger.obj.Blog;

@SuppressWarnings("serial")
public class BlogViewerServlet extends HttpServlet {
	
	public void init(ServletConfig config) throws ServletException 
	{  
		super.init(config); //added this line then it worked  
	}
	
	public void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws IOException,ServletException {
		resp.setContentType(ConstantHelper.CONTENT_TYPE_UTF8);
		resp.setCharacterEncoding(ConstantHelper.CHARACTER_ENCODING_UTF8);	    
		doPost(req, resp);
	}//doGet
	

	public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException,ServletException
	{
		//get the post id
		String lsPathInfo = req.getPathInfo();
		String lsPostId = lsPathInfo.split("/")[1];
		//search cookie
		
		//if no post id found, use api to get
		
		try 
		{
			Blog loBlog = this.getBlog(lsPostId);
			
			req.setAttribute(ConstantHelper.BLOGGER_NAME_BLOG, loBlog);
				
			getServletContext().getRequestDispatcher(PropertiesHelper.getBlogDetailPage()).forward(req, resp);
		} catch (ServiceException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}//doPost
	
	private  Blog getBlog(String lsPostId) throws IOException, ServiceException
	{
		GoogleService myService = new GoogleService(ConstantHelper.SERVICE_NAME_BLOGGER, ConstantHelper.APPLICATION_NAME_BLOGGER);
		myService.setUserCredentials(PropertiesHelper.getBlogUser(), PropertiesHelper.getBlogPwd());
		
		
		// Request the last 5 feed
		  String lsPostFeed = PropertiesHelper.getBlogFeedUrl() + "/" + lsPostId;
		  final URL feedUrl = new URL(lsPostFeed);
		  //BlogFeed resultFeed = myService.getFeed(feedUrl, BlogFeed.class);
		  Entry loEntry = myService.getEntry(feedUrl, Entry.class);
		  
		  if (loEntry == null)
		  {
				 //jump jump jump 
				  return null;
		  }//if (loEntry == null) 
		  
		  Blog loBlog = new Blog();
		 
		  loBlog.setBlogTitle(loEntry.getTitle().getPlainText());
		  loBlog.setPublishDate(loEntry.getPublished());
		  TextConstruct loBlogText = ((TextContent) loEntry.getContent()).getContent();
		  String lsBlogHtml = ((HtmlTextConstruct)loBlogText).getHtml();
		  loBlog.setBlogContent(lsBlogHtml);
		  
			  return loBlog;
			  
	}//getBlogList
}//HkugBloggerServlet
